package com.ldc.commonlibs;

import android.app.Application;
import android.content.res.Configuration;

import androidx.annotation.NonNull;

import com.alibaba.android.arouter.launcher.ARouter;
import com.ldc.commonlibs.config.AppConfig;
import com.ldc.commonlibs.common.ComponentContext;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.MaterialHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liudc
 * @since 2022/7/3 13:33
 */
public abstract class ApplicationBase extends Application {
    protected final String TAG = this.getClass().getSimpleName();
    private final List<Class<? extends AppInitBase>> clazzList = new ArrayList<>();
    private final List<AppInitBase> appInitList = new ArrayList<>();

    @Override
    public void onCreate() {
        super.onCreate();
        ComponentContext.initContext(this);
        init(this);
        registerARouter(this);
        initSmartRefreshView();
        initAppInit(this);

    }

    protected abstract void init(Application application);

    protected void register(Class<? extends AppInitBase> appInitBase) {
        clazzList.add(appInitBase);
    }

    private void initAppInit(Application application) {
        try {
            for (Class<? extends AppInitBase> clazz : clazzList) {
                AppInitBase appInitBase = clazz.newInstance();
                appInitBase.setApplication(application);
                appInitBase.onCreate();
                appInitList.add(appInitBase);
            }
        } catch (Exception ignore) {
        }
    }

    private void registerARouter(Application application) {
        if (AppConfig.isDebug) {
            ARouter.openDebug();
            ARouter.openLog();
        }
        ARouter.init(application);
    }

    private void initSmartRefreshView() {
        SmartRefreshLayout.setDefaultRefreshHeaderCreator((context, layout) -> new MaterialHeader(context));
        SmartRefreshLayout.setDefaultRefreshFooterCreator(((context, layout) -> new ClassicsFooter(context)));
    }


    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        for (AppInitBase app : appInitList) {
            app.configurationChanged(newConfig);
        }
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        for (AppInitBase app : appInitList) {
            app.onLowMemory();
        }
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        for (AppInitBase app : appInitList) {
            app.onTerminate();
        }
    }
}
